package fhv.at.imageprocessing.andImage;

import java.io.Serializable;

import javax.media.jai.PlanarImage;

import fhv.at.imageprocessing.ImageChangedEvent;
import fhv.at.imageprocessing.ImageChangedListener;
import fhv.at.imageprocessing.ImageHelper;
import fhv.at.imageprocessing.ImageNeededEvent;
import fhv.at.imageprocessing.ImageProcessor;

/**
 * And image bean
 * 
 * @author phru
 * 
 */
public class AndImage implements ImageChangedListener, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final ImageHelper imageHelper;
	private PlanarImage planarImage;
	private final PlanarImage[] planarImages;

	public AndImage() {
		int maxParents = 2;
		planarImages = new PlanarImage[maxParents];
		imageHelper = new ImageHelper(maxParents, this);
	}

	/* Eigentliche Bildbearbeitung */
	@Override
	public void manipulateImage() {
		if ((planarImages[0] != null) && (planarImages[1] != null)) {
			ImageProcessor ip = ImageProcessor.getInstance();
			planarImage = ip.getAND(planarImages[0], planarImages[1]);
			imageHelper.fireImageChangedEvent();
		}
	}

	/* Implementation fur Eventregistrierung */
	@Override
	public void addImageChangedListener(ImageChangedListener icl) {
		imageHelper.addImageChangedListener(icl);
	}

	@Override
	public void removeImageChangedListener(ImageChangedListener icl) {
		imageHelper.removeImageChangedListener(icl);
	}

	@Override
	public void addImageNeededListener(ImageChangedListener icl) {
		imageHelper.addImageNeededListener(icl);
	}

	@Override
	public void removeImageNeededListener(ImageChangedListener icl) {
		imageHelper.removeImageNeededListener(icl);
	}

	/* Implementation fur ImageChangedListener */
	@Override
	public void imageValueChanged(ImageChangedEvent ice) {
		System.out.println(getClass().getSimpleName() + " imageValueChanged");
		planarImages[imageHelper.getPos(ice)] = imageHelper.getPlanarImage(ice);
		manipulateImage();
	}

	@Override
	public void imageNeeded(ImageNeededEvent ice) {
		System.out.println(getClass().getSimpleName() + " imageNeeded");
		imageHelper.fireImageChangedEvent();
		// imageHelper.fireImageChangedEvent(ice);
	}

	@Override
	public ImageChangedListener getRefFromSource() {
		return this;
	}

	@Override
	public PlanarImage getPlanarImage() {
		return planarImage;
	}

}
